package com.zhangsun.multiConfig.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zhangsun.base.common.constant.ConfigConstant;
import com.zhangsun.base.framework.common.Config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = ConfigConstant.DB1_MAPPER_PACKAGE, sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class DB1Configuration {

    /**
     * mybatis-plus分页插件
     */
    @Bean(name = "db1PaginationInterceptor")
    @Primary
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    @Bean(name = "db1DataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource dataSource() {
        return new DruidDataSource();
    }

    /**
     * 事务管理
     *
     * @param dataSource 数据源
     * @return 事务管理器
     */
    @Bean(name = "db1TransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("db1DataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "db1SqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("db1DataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactory = Config.getMybatisSqlSessionFactoryBean(dataSource, ConfigConstant.DB1_ENTITY_PACKAGE, ConfigConstant.DB1_ENUM_PACKAGE, paginationInterceptor(), ConfigConstant.DB1_MAPPER_LOCATION);
        return sqlSessionFactory.getObject();
    }

    @Bean(name = "db1SqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("db1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}
